package xpn.platform.modules.security;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import xpn.platform.common.config.XpnPlatformConfig;

/**
 * 自定义Shiro会话管理器
 * 
 * @author bobatkm Sep 7, 2017
 *
 */
public class ShiroSessionManager extends DefaultWebSessionManager {
	@Autowired
	XpnPlatformConfig xpnPlatformConfig;

	/**
	 * 重载取sessionId的方法：优先从请求参数或者请求头中读取，如果没有，则调用被重载的方法取
	 */
	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		String xpnTokenName = xpnPlatformConfig.getSecurity().getAuthenticationTokenName();
		String sessionId = httpRequest.getHeader(xpnTokenName);

		if (sessionId == null || "".equals(sessionId)) {
			sessionId = httpRequest.getParameter(xpnTokenName);
		}

		if (sessionId == null || "".equals(sessionId)) {
			return super.getSessionId(request, response);
		}

		return sessionId;
	}
}
